<!--
* @description 批量新增资产
* @author zywu
* @date 2021/01/19 15:53:40
!-->
<template>
  <div class="batch-add" v-loading="loading">
    <div v-if="activeStep>0" class="my-steps">
      <el-steps :space="200" :active="activeStep" finish-status="success">
        <el-step title="开始"></el-step>
        <el-step title="填写个体信息"></el-step>
        <el-step title="填写公共信息"></el-step>
        <el-step title="预览"></el-step>
      </el-steps>
    </div>
    <!-- 1.资产类别 -->
    <el-form
      class="form-asset-type"
      v-show="activeStep==0"
      label-width="150px"
      :model="dataForm"
      :rules="dataRules"
      ref="dataForm0"
    >
      <el-form-item label="系统与类别：" prop="categoryId">
        <tree-select
          ref="myTreeSelect"
          v-model="dataForm.categoryId"
          @node-click="handleCategoryNodeClick"
          filterable
          :data="typeList"
          :defaultProps="typeDefaultProps"
          :checkedKeys="defaultCheckedCategoryId"
          :nodeKey="typeNodeKey"
        ></tree-select>
      </el-form-item>
      <el-form-item label>
        <el-tag
          v-for="(item,i) in topTypes"
          :key="i"
          :effect="item.id==dataForm.categoryId?'dark':'plain'"
          @click="handleChooseType(item)"
          style="cursor:pointer;"
        >{{item.name}}</el-tag>
      </el-form-item>
    </el-form>
    <!-- 2.基础信息1 -->
    <div class="form-baseinfo" v-show="activeStep==1" style="padding:0 15px;">
      <el-row :gutter="5" style="padding:0 0 20px;">
        <el-col :span="1" class="text-center">序号</el-col>
        <el-col :span="3" class="text-center">
          <span class="red">*</span>名称
        </el-col>
        <el-col :span="3" class="text-center">
          <span class="red">*</span>所在建筑物
        </el-col>
        <el-col :span="3" class="text-center">
          <span class="red">*</span>具体位置
        </el-col>
        <el-col :span="2" class="text-center">状态</el-col>
        <el-col :span="2" class="text-center">编号</el-col>
        <el-col :span="3" class="text-center">生产日期</el-col>
        <el-col :span="2" class="text-center">保质期</el-col>
        <el-col :span="3" class="text-center">关联物联设备</el-col>
        <el-col :span="2" class="text-center"></el-col>
      </el-row>
      <el-form
        class="grid-form"
        label-width="0"
        :model="dataForm"
        :rules="dataRules"
        ref="dataForm1"
        :style="{ height:height+'px' }"
      >
        <el-row :gutter="5" v-for="(item,i) in dataForm.dataList" :key="item.key">
          <el-col :span="1" class="text-center" style="line-height:40px;">{{i+1}}</el-col>
          <el-col :span="3">
            <el-form-item :prop="'dataList.'+i+'.name'" :rules="dataRules.name">
              <el-input
                :ref="'name'+i"
                v-model="item.name"
                clearable
                :placeholder="categoryName"
                @keyup.native.up="handleKeyup('up',i,'name')"
                @keyup.native.down="handleKeyup('down',i,'name')"
                @keyup.native.left="handleKeyup('left',i,'name')"
                @keyup.native.right="handleKeyup('right',i,'name')"
                @keyup.native.enter="handleKeyup('enter',i)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :prop="'dataList.'+i+'.fbsId'" :rules="dataRules.fbsId">
              <tree-select
                :ref="'fbsId'+i"
                class="asset-build"
                v-model="item.fbsId"
                :node-clickable="nodeClickable"
                filterable
                :data="newBuildList"
                :defaultProps="buildDefaultProps"
                :checkedKeys="defaultCheckedFbsId"
                @node-click="(e)=>{handleNodeClick(e,i)}"
                :nodeKey="buildNodeKey"
                @keyup.native.up="handleKeyup('up',i,'fbsId')"
                @keyup.native.down="handleKeyup('down',i,'fbsId')"
                @keyup.native.left="handleKeyup('left',i,'fbsId')"
                @keyup.native.right="handleKeyup('right',i,'fbsId')"
                @keyup.native.enter="handleKeyup('enter',i)"
              ></tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :prop="'dataList.'+i+'.location'" :rules="dataRules.location">
              <el-input
                :ref="'location'+i"
                v-model="item.location"
                auto-complete="off"
                clearable
                placeholder="请输入具体位置"
                @keyup.native.up="handleKeyup('up',i,'location')"
                @keyup.native.down="handleKeyup('down',i,'location')"
                @keyup.native.left="handleKeyup('left',i,'location')"
                @keyup.native.right="handleKeyup('right',i,'location')"
                @keyup.native.enter="handleKeyup('enter',i)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item :prop="'dataList.'+i+'.status'" :rules="dataRules.status">
              <el-select :ref="'status'+i" v-model="item.status" placeholder="请选择">
                <el-option label="在用" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item :prop="'dataList.'+i+'.serialNumber'" :rules="dataRules.serialNumber">
              <el-input
                :ref="'serialNumber'+i"
                v-model="item.serialNumber"
                clearable
                @keyup.native.up="handleKeyup('up',i,'serialNumber')"
                @keyup.native.down="handleKeyup('down',i,'serialNumber')"
                @keyup.native.left="handleKeyup('left',i,'serialNumber')"
                @keyup.native.right="handleKeyup('right',i,'serialNumber')"
                @keyup.native.enter="handleKeyup('enter',i)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item
              :prop="'dataList.'+i+'.productionTimeStr'"
              :rules="dataRules.productionTimeStr"
            >
              <el-date-picker
                :ref="'productionTimeStr'+i"
                v-model="item.productionTimeStr"
                type="date"
                placeholder="选择日期时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item :prop="'dataList.'+i+'.yearNum'">
              <el-input
                :ref="'yearNum'+i"
                v-model="item.yearNum"
                @blur="handleNumberKeyup(i)"
                @keyup.native.up="handleKeyup('up',i,'yearNum')"
                @keyup.native.down="handleKeyup('down',i,'yearNum')"
                @keyup.native.left="handleKeyup('left',i,'yearNum')"
                @keyup.native.right="handleKeyup('right',i,'yearNum')"
                @keyup.native.enter="handleKeyup('enter',i)"
                style="margin-left:10px;width:70px;"
              ></el-input>&nbsp;年
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item :prop="'dataList.'+i+'.relateFcIds'">
              <el-select
                :ref="'relateFcIds'+i"
                multiple
                :collapse-tags="true"
                v-model="item.relateFcIds"
                placeholder="请选择关联物联设备"
                filterable
                :filter-method="e=>{getFcfOptions(e,i,item)}"
                :loading="item.relateFcIdsSelectloading"
                @change="handleRelateFcChange(i)"
              >
                <el-option
                  v-for="(n) in item.relateFcOptions"
                  :key="n.id"
                  :label="n.name"
                  :value="n.id"
                ></el-option>
                <el-pagination
                  @current-change="e=>{handleCurrentChange(e,i,item)}"
                  small
                  :current-page.sync="item.relateFcPageIndex"
                  layout="total, prev, pager, next"
                  :total="item.relateFcTotal"
                ></el-pagination>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <i class="btn-gird el-icon-plus" @click="handleAdd(i)"></i>
            <i
              v-if="dataForm.dataList.length>1"
              class="btn-gird el-icon-minus"
              @click="handleMinus(i)"
            ></i>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 3.基础信息2 -->
    <el-form
      class="form-asset-type"
      v-show="activeStep==2"
      label-width="150px"
      :model="dataForm"
      :rules="dataRules"
      ref="dataForm2"
    >
      <!-- <el-form-item label="状态：" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio label="0">在用</el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>-->
      <el-form-item label="标识类型：" prop="visualCodeType">
        <el-row>
          <el-radio v-model="dataForm.visualCodeType" label="0">单点型-由系统自动生成二维码</el-radio>
          <el-radio v-model="dataForm.visualCodeType" label="2">区域型</el-radio>
        </el-row>
      </el-form-item>
      <el-form-item label="维保公司：" prop="maintainCompanyType">
        <el-row>
          <el-radio v-model="dataForm.maintainCompanyType" label="1">由单位的维保公司维保</el-radio>
          <el-radio v-model="dataForm.maintainCompanyType" label="0">其他公司</el-radio>
        </el-row>
      </el-form-item>
      <el-form-item label="型号：" prop="model">
        <el-input v-model="dataForm.model" auto-complete="off" placeholder="请输入型号" clearable></el-input>
      </el-form-item>
      <el-form-item label="品牌：" prop="brand">
        <el-input v-model="dataForm.brand" auto-complete="off" placeholder="请输入品牌名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="生产厂家：" prop="producerName">
        <el-input
          v-model="dataForm.producerName"
          auto-complete="off"
          placeholder="请输入生产厂家名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="备注：" prop="remarks">
        <el-input
          type="textarea"
          v-model="dataForm.remarks"
          auto-complete="off"
          placeholder="添加资产的单独信息"
        ></el-input>
      </el-form-item>
    </el-form>
    <!-- 4.预览 -->
    <div v-show="activeStep==3">
      <el-table border :data="dataList" :height="tableHeight">
        <el-table-column label="序号" width="60" align="center">
          <template v-slot="sc">{{sc.$index+1}}</template>
        </el-table-column>
        <el-table-column label="系统与类别" prop="categoryName" width="140">
          <template>{{categoryName}}</template>
        </el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="所在建筑物" prop="buildingName"></el-table-column>
        <el-table-column label="具体位置" prop="location"></el-table-column>
        <el-table-column label="状态" prop="status" width="70">
          <template v-slot="sc">{{sc.row.status==1?'停用':'在用'}}</template>
        </el-table-column>
        <el-table-column label="编号" prop="serialNumber"></el-table-column>
        <el-table-column label="生产日期" prop="productionTimeStr" width="120">
          <template v-slot="sc">{{sc.row.productionTimeStr.substr(0,10)}}</template>
        </el-table-column>
        <el-table-column label="保质期" prop="yearNum" width="80">
          <template v-slot="sc">
            <span v-if="sc.row.yearNum">{{sc.row.yearNum}}年</span>
          </template>
        </el-table-column>
        <el-table-column label="关联物联设备" prop="relateFcNames"></el-table-column>
        <!-- <el-table-column label="型号" prop="model">
          <template>{{dataForm.model}}</template>
        </el-table-column>
        <el-table-column label="品牌" prop="brand">
          <template>{{dataForm.brand}}</template>
        </el-table-column>
        <el-table-column label="生产厂家" prop="producerName">
          <template>{{dataForm.producerName}}</template>
        </el-table-column>
        <el-table-column label="标识类型" prop width="85">
          <template>{{visualCodeTypes[Number(dataForm.visualCodeType||0)]}}</template>
        </el-table-column>
        <el-table-column label="维保公司" prop width="170">
          <template>{{dataForm.maintainCompanyType==1?'由单位的维保公司维保':'其他公司'}}</template>
        </el-table-column>-->
      </el-table>
      <div
        class="row-info"
        style="margin-top:10px;"
      >标识类型：{{visualCodeTypes[Number(dataForm.visualCodeType||0)]}}</div>
      <div class="row-info">维保公司：{{dataForm.maintainCompanyType==1?'由单位的维保公司维保':'其他公司'}}</div>
      <div class="row-info">型号：{{dataForm.model}}</div>
      <div class="row-info">品牌：{{dataForm.brand}}</div>
      <div class="row-info">生产厂家：{{dataForm.producerName}}</div>
      <div class="row-info">备注：{{dataForm.remarks}}</div>
    </div>
    <div class="wrap-buttons">
      <div class="add-row" v-if="activeStep==1">
        <el-button icon="el-icon-plus" @click="handleMultiAdd()"></el-button>
        <el-input-number v-model="amount" :controls="false" :min="1" :max="50"></el-input-number>行
      </div>
      <el-button v-if="activeStep==1||activeStep==2" @click="handleReset">重置</el-button>
      <el-button v-if="!saved&&activeStep>1" type="primary" plain @click="handlePrev">上一步</el-button>
      <el-button v-if="!saved&&activeStep>0&&activeStep<3" type="primary" @click="handleNext">下一步</el-button>
      <el-button v-if="!saved&&activeStep==0" type="primary" @click="handleNext">开始</el-button>
      <el-button v-if="!saved&&activeStep==3" type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import {
  getAssetsCategoryId,
  batchAddAssets,
  assetCategoryQuick,
} from '@/api/assets'
import { getFcfSelectList } from '@/api/fcf'

// 缓存每一步的数据
var cacheData = ['', '', '']
var defaultForm2 = () => {
  return {
    // status: '0',
    visualCodeType: '0',
    maintainCompanyType: '1',
    brand: '',
    model: '',
    producerName: '',
    remarks: '',
  }
}
var relateFcOptions = []
var relateFcTotal = 0

export default {
  props: {
    organizationId: {
      type: [Number, String],
      default: '',
    },
    buildList: {
      type: Array,
      default: function () {
        return []
      },
    },
  },
  data() {
    return {
      amount: 10,
      height: 500,
      tableHeight: 500,
      showChooseFc: false,
      showCategoryTip: false,
      loading: false,
      activeStep: 0,
      // 消防系统-资产类别
      typeList: [],
      typeDefaultProps: {
        children: 'categoryList',
        label: 'name',
        value: 'id',
      },
      typeNodeKey: 'id',
      defaultCheckedCategoryId: [],
      categoryName: '',

      // 建筑物
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedFbsId: [],
      newBuildList: [],

      topTypes: [],
      dataForm: {
        categoryId: '',
        dataList: [],
        ...defaultForm2(),
      },
      dataRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'change' }],
        // status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        categoryId: [
          { required: true, message: '请选择系统与类别', trigger: 'change' },
        ],
        fbsId: [
          { required: true, message: '请选择所在建筑物', trigger: 'blur' },
        ],
        location: [
          { required: true, message: '请输入具体位置', trigger: 'change' },
        ],
        visualCodeType: [
          { required: true, message: '请选择标识类型', trigger: 'change' },
        ],
        maintainCompanyType: [
          { required: true, message: '请选择维保公司', trigger: 'change' },
        ],
        remarks: [
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字',
            trigger: 'change',
          },
        ],
        serialNumber: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        model: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        brand: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        producerName: [
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' },
        ],
        remarks: [
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字',
            trigger: 'blur',
          },
        ],
      },
      dataList: [],
      visualCodeTypes: ['单点型', '单点型', '区域型'],
      saved: false, // 是否已保存成功
    }
  },

  components: {
    TreeSelect,
  },

  computed: {},

  watch: {
    activeStep(val) {
      if (val == 3) {
        this.dataList = this.dataForm.dataList.filter((n) => {
          return n.name && n.fbsId && n.location
        })
      }
    },
  },

  created() {
    cacheData = ['', '', '']
    this.saved = false
    this.newBuildList = this.buildList.map((n) => {
      return n
    })
    this.getTypeList()
    this.assetCategoryQuick()
  },

  mounted() {
    this.$nextTick(() => {
      this.$refs.dataForm0.clearValidate()
    })
    this.getFcfOptions()
  },

  methods: {
    handleReset() {
      this.$confirm('确定重置当前表单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$refs['dataForm' + this.activeStep].resetFields()
          if (this.activeStep == 1) {
            for (var i = 0; i < this.dataForm.dataList.length; i++) {
              this.$refs['fbsId' + i][0].clearSelected()
            }
          }
        })
        .catch(() => {})
    },
    handleRelateFcChange(i) {
      this.$nextTick(() => {
        let selected = this.$refs['relateFcIds' + i][0].selected
        let label = selected
          .map((n) => {
            return n.$props.label
          })
          .join(',')
        this.$set(this.dataForm.dataList[i], 'relateFcNames', label)
      })
    },
    handleConfirmFc() {
      this.showChooseFc = false
    },
    getFcfOptions(name, pageChange, item) {
      // 重新搜索时页码复原
      if (!pageChange && item) {
        this.$set(item, 'relateFcPageIndex', 1)
      }
      let parames = {
        fbsId: 0,
        organizationId: this.organizationId,
        parentId: 0,
        pageIndex: item ? item.relateFcPageIndex - 1 : 0,
        pageSize: 10,
        name: name || '',
      }
      item && this.$set(item, 'relateFcIdsSelectloading', true)
      // 获取关联物联设备
      getFcfSelectList(parames).then((res) => {
        if (item) {
          this.$set(item, 'relateFcOptions', res.data)
          this.$set(item, 'relateFcTotal', res.total)
          this.$set(item, 'relateFcIdsSelectloading', false)
        } else {
          relateFcOptions = res.data
          relateFcTotal = res.total
        }
      })
    },
    handleCurrentChange(currentpage, i, item) {
      let $select = this.$refs['relateFcIds' + i][0]
      this.$set(item, 'relateFcPageIndex', currentpage)
      this.getFcfOptions($select.$refs.input.value, true, item)
    },
    handleKeyup(key, i, name) {
      switch (key) {
        case 'up':
          if (i > 0) {
            this.$refs['fbsId' + i][0].blur()
            this.$refs[`${name}${i - 1}`][0].focus()
          }
          break
        case 'down':
          if (i < this.dataForm.dataList.length - 1) {
            this.$refs['fbsId' + i][0].blur()
            this.$refs[`${name}${i + 1}`][0].focus()
          }
          break
        case 'left':
          let map = {
            fbsId: 'name',
            location: 'fbsId',
            status: 'location',
            serialNumber: 'status',
            productionTimeStr: 'serialNumber',
            yearNum: 'productionTimeStr',
            relateFcIds: 'yearNum',
          }
          if (map[name]) {
            this.$refs['fbsId' + i][0].blur()
            this.$refs[`${map[name]}${i}`][0].focus()
          }
          break
        case 'right':
          let map2 = {
            name: 'fbsId',
            fbsId: 'location',
            location: 'status',
            status: 'serialNumber',
            serialNumber: 'productionTimeStr',
            productionTimeStr: 'yearNum',
            yearNum: 'relateFcIds',
          }
          if (map2[name]) {
            this.$refs['fbsId' + i][0].blur()
            this.$refs[`${map2[name]}${i}`][0].focus()
          }
          break
        case 'enter':
          if (i < this.dataForm.dataList.length - 1) {
            this.$refs['fbsId' + i][0].blur()
            this.$refs[`name${i + 1}`][0].focus()
          }
          break
        default:
          break
      }
    },
    handleNumberKeyup(i) {
      if (this.dataForm.dataList[i].yearNum === '') return
      if (isNaN(Number(this.dataForm.dataList[i].yearNum))) {
        this.dataForm.dataList[i].yearNum = ''
      } else if (this.dataForm.dataList[i].yearNum < 1) {
        this.dataForm.dataList[i].yearNum = 1
      } else {
        this.dataForm.dataList[i].yearNum = parseInt(
          this.dataForm.dataList[i].yearNum
        )
      }
    },
    getTypeList() {
      getAssetsCategoryId().then((res) => {
        if (res.status === 200) {
          let newArr = res.data
          // 系统与类别的系统节点增加disabled
          for (var i = 0, len = newArr.length; i < len; i++) {
            newArr[i].disabled = true
          }
          this.typeList = newArr
        }
      })
    },
    assetCategoryQuick() {
      assetCategoryQuick().then((res) => {
        this.topTypes = res.data
      })
    },
    initDataList() {
      this.dataForm.dataList = []
      this.$nextTick(() => {
        this.pushDataList(10)
      })
    },
    pushDataList(len) {
      let arr = []
      for (var i = 0; i < len; i++) {
        arr.push({
          name: '',
          fbsId: '',
          location: '',
          status: '0',
          serialNumber: '',
          productionTimeStr: '',
          key: new Date().getTime() + i,
          relateFcIdsSelectloading: false,
          relateFcOptions: relateFcOptions, // 关联物联设备
          relateFcPageIndex: 1,
          relateFcTotal: relateFcTotal,
          relateFcIds: [],
          yearNum: '',
        })
      }
      this.dataForm.dataList = this.dataForm.dataList.concat(arr)
    },
    // 点击类别节点
    handleCategoryNodeClick(val) {
      let data = cacheData[0]
      this.categoryName = val ? val.name : ''
      this.showCategoryTip =
        val.id && data && val.id !== JSON.parse(data).categoryId
    },
    handleChooseType(item) {
      let node = this.$refs.myTreeSelect.$refs.tree.getNode(item.id)
      if (node) {
        this.$refs.myTreeSelect.handleNodeClick(node.data, node)
        this.$refs.myTreeSelect.isShowSelect = false
        this.dataForm.categoryId = item.id
        this.$refs.dataForm0.validateField('categoryId')
      }
    },
    // 建筑物节点是否可点击
    nodeClickable(val) {
      if (val.type == 4 || val.type == 5) {
        return true
      } else {
        this.$message.warning('请选择楼层及楼层以下')
        return false
      }
    },
    // 点击建筑物节点
    handleNodeClick(val, i) {
      this.dataForm.dataList[i].buildingName = val ? val.text : ''
      this.$nextTick(() => {
        this.$refs.dataForm1.validateField(`dataList.${i}.fbsId`)
      })
    },
    handleAdd(index) {
      if (this.dataForm.dataList.length >= 50) {
        return this.$message.warning('目前资产批量新增已到达上限50')
      }
      this.dataForm.dataList.splice(index + 1, 0, {
        name: '',
        fbsId: '',
        location: '',
        status: '0',
        serialNumber: '',
        productionTimeStr: '',
        relateFcIdsSelectloading: false,
        relateFcOptions: relateFcOptions, // 关联物联设备
        relateFcPageIndex: 1,
        relateFcTotal: relateFcTotal,
        relateFcIds: [],
        yearNum: '',
        key: new Date().getTime(),
      })
    },
    handleMultiAdd() {
      if (this.dataForm.dataList.length + this.amount > 50) {
        return this.$message.warning('资产批量新增最多50条')
      }
      this.pushDataList(this.amount)
      this.$message.success('添加' + this.amount + '行成功')
    },
    handleMinus(index) {
      let item = this.dataForm.dataList[index]
      if (
        item.name ||
        item.fbsId ||
        item.location ||
        item.serialNumber ||
        item.productionTimeStr ||
        item.relateFcIds.length > 0
      ) {
        this.$confirm('确定删除该行吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.dataForm.dataList.splice(index, 1)
          })
          .catch(() => {})
      } else {
        this.dataForm.dataList.splice(index, 1)
      }
    },
    // 上一步
    handlePrev() {
      this.activeStep--
    },
    // 更新当前步骤缓存数据
    updateCacheData(step) {
      cacheData[step] = this.getDataByStep(step)
    },
    // 提取每一步的数据
    getDataByStep(step) {
      let data = {}
      if (step == 0) {
        data = {
          categoryId: this.dataForm.categoryId,
        }
      } else if (step == 1) {
        data = {
          dataList: this.dataForm.dataList.filter((n) => {
            return n.name && n.fbsId && n.location
          }),
        }
      } else if (step == 2) {
        let {
          visualCodeType,
          maintainCompanyType,
          model,
          brand,
          producerName,
          remarks,
        } = this.dataForm
        data = {
          visualCodeType,
          maintainCompanyType,
          model,
          brand,
          producerName,
          remarks,
        }
      }
      return JSON.stringify(data)
    },
    validateGrid() {
      let fields = ['name', 'fbsId', 'location', 'serialNumber']
      let isPass = true
      let arr = this.dataForm.dataList.filter((n) => {
        return n.name || n.fbsId || n.location || n.serialNumber
      })
      if (arr.length == 0) {
        isPass = false
        this.$message.warning('请至少填写完整一个资产信息')
      } else {
        this.dataForm.dataList.forEach((n, i) => {
          if (
            n.name ||
            n.fbsId ||
            n.location ||
            n.serialNumber ||
            n.productionTimeStr ||
            n.relateFcIds.length > 0
          ) {
            fields.forEach((f) => {
              this.$refs.dataForm1.validateField(
                `dataList.${i}.${f}`,
                (err) => {
                  if (err) {
                    isPass = false
                  }
                }
              )
            })
          }
        })
      }
      return isPass
    },
    onValidatePass(step) {
      this.activeStep++
      this.height = document.documentElement.clientHeight - 290
      this.tableHeight = document.documentElement.clientHeight - 380
      if (step == 0) {
        this.$emit('larger')
        if (this.dataForm.dataList.length == 0) {
          setTimeout(() => {
            this.initDataList()
          }, 100)
        }
      }
      this.updateCacheData(step)
    },
    // 校验
    validStep(step) {
      if (step == 1) {
        let valid = this.validateGrid()
        if (valid) {
          this.onValidatePass(step)
        }
      } else {
        this.$refs['dataForm' + step].validate((valid) => {
          if (valid) {
            this.onValidatePass(step)
          }
        })
      }
    },
    // 下一步
    handleNext() {
      if (this.activeStep < 3) {
        this.validStep(this.activeStep)
      } else {
        this.saveForm()
      }
    },
    // 保存
    handleSave() {
      this.loading = true
      batchAddAssets({
        orgId: this.organizationId,
        ...this.dataForm,
        resultDetail: JSON.stringify(
          this.dataList.map((n) => {
            return {
              name: n.name,
              fbsId: n.fbsId,
              location: n.location,
              status: n.status,
              serialNumber: n.serialNumber,
              productionTimeStr: n.productionTimeStr,
              relateFcIds: n.relateFcIds.join(','),
              yearNum: n.yearNum || 10,
            }
          })
        ),
        dataList: undefined,
      })
        .then((res) => {
          if (res.status == 200) {
            this.saved = true
            this.$message.success('批量新增资产成功')
            this.$emit('refresh-list')
          } else {
            this.$message.error(res.info)
          }
          this.loading = false
        })
        .catch((res) => {
          this.$message.error('系统异常')
          this.loading = false
        })
    },
  },
}
</script>
<style lang='scss'>
.batch-add {
  .el-table__body-wrapper {
    overflow-y: auto;
  }
  .row-info {
    line-height: 20px;
  }
  .my-steps {
    margin: 10px 0 30px 0;
    display: flex;
    justify-content: center;
    .el-steps {
      width: 800px;
    }
  }
  .el-tag {
    margin: 0 10px 10px 0;
  }
  .el-form {
    .el-form-item {
      margin-bottom: 22px;
    }
  }
  .grid-form {
    padding: 0 15px 0 0;
    overflow-y: auto;
  }
  .btn-gird {
    margin: 0 5px;
    width: 40px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
  }
  .form-asset-type {
    margin-top: 20px;
    .el-input-number,
    .el-select,
    .el-input {
      width: 500px !important;
    }
    .el-textarea {
      width: 800px !important;
    }
  }
  .form-baseinfo {
    overflow-y: auto;
    .el-select {
      width: 100% !important;
    }
  }
  .el-input-number {
    .el-input__inner {
      text-align: left;
    }
  }
  .wrap-buttons {
    position: relative;
    padding: 20px 0;
    text-align: center;
    .add-row {
      position: absolute;
      top: 20px;
      right: 50px;
    }
    .el-button {
      margin-right: 10px;
    }
    .el-input-number {
      width: 80px;
      margin-right: 5px;
    }
  }
  .red {
    color: red;
  }
}
</style>